import { Component, OnInit, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core';
import { InputNumber, InputBoolean } from 'ng-zorro-antd';
import { NotificationService } from 'app/shared/service/notification.service';

@Component({
    selector: 'itmp-pagination',
    templateUrl: './pagination.component.html',
    styleUrls: ['./pagination.component.css']
})
export class PaginationComponent implements OnInit {
    private _pageSize = 10;
    private _totalEle = 10;
    @ViewChild('pageInput') pageInput: ElementRef;
    @Input() pageNum = 1;
    @Input()
    set totalEle(totalEle: number) {
        if (!totalEle) {
            return;
        }
        this.calcPageEnd(this.pageSize, totalEle);
        this._totalEle = totalEle;
    }

    get totalEle(): number {
        return this._totalEle;
    }
    // 单页实际数据条数
    @Input()
    @InputNumber()
    count = 0;
    @Input()
    @InputBoolean()
    showCountInfo = true;
    @Input()
    set pageSize(pageSize: number) {
        this.calcPageEnd(pageSize, this.totalEle);
        this._pageSize = pageSize;
    }
    get pageSize(): number {
        return this._pageSize;
    }
    @Input() pageSizeOptions: Array<number> = [10, 20, 30, 40];

    @Output() pageSizeChange = new EventEmitter<number>();
    @Output() pageNumChange = new EventEmitter<number>();
    get eleInfo(): string {
        const start = (this.pageNum - 1) * this.pageSize + 1;
        const end = start + this.count - 1;
        const lang = localStorage.getItem('itmp_lang');
        if (lang === 'en') {
            return `Showing ${start} to ${end} of ${this.totalEle}`;
        } else if (lang === 'zh') {
            return `显示 ${start} 到 ${end} 共 ${this.totalEle}`;
        } else if (lang === 'vi') {
            return `Hiển thị ${start} Đến ${end} Toàn bộ ${this.totalEle}`;
        }
    }

    pageEnd = 1;
    constructor(private msg: NotificationService) {}

    onPageSizeChange(pageSize: number) {
        this.pageSizeChange.emit((this.pageSize = pageSize));
    }

    onPageChange(pageNum: number) {
        this.pageNumChange.emit((this.pageNum = pageNum));
    }

    jump(pageNum: any) {
        const valid = !isNaN(pageNum) && pageNum > 0 && pageNum % 1 === 0 && pageNum <= this.pageEnd;
        if (valid) {
            if (this.pageNum !== +pageNum) {
                this.pageNumChange.emit((this.pageNum = +pageNum));
            }
        } else {
            this.msg.notify({ type: 'warning', path: 'Share.Pagination.Page_Num_Invaild_Notify' });
            this.pageNumChange.emit(1);
            this.pageNum = 1;
            this.pageInput.nativeElement.value = '1';
        }
    }

    gotoPageEnterHandle(_e, pageNum: any) {
        if (_e.keyCode === 13) {
            this.jump(pageNum);
        }
    }

    calcPageEnd(pageSize: number, totalEle: number): void {
        this.pageEnd = Math.ceil(totalEle / (pageSize || 10)) || 1;
    }

    ngOnInit() {}
}
